package com.nitty.cash.loop.ui.presenter

import com.nitty.cash.loop.R
import com.nitty.cash.loop.common.CommonPresenter
import com.nitty.cash.loop.configs.NittyApiPath
import com.nitty.cash.loop.configs.NittyApiUrl
import com.nitty.cash.loop.configs.NittyApiUrl.addCommonParams
import com.nitty.cash.loop.event.NittyEventData
import com.nitty.cash.loop.request.IHttpCallback
import com.nitty.cash.loop.ui.contract.IViewContract
import com.nitty.cash.loop.utils.NittyTitleBarUtil
import com.nitty.cash.loop.utils.helper.NittyCreditStatusHelper
import com.nitty.cash.loop.utils.helper.NittyOrderHelper
import com.nitty.cash.loop.utils.helper.NittyProcessHelper
import org.json.JSONObject

/**
 * NittyCash
 * @Author wwdeng
 * @CreateTime: 2024/11/22 11:59
 * @Annotation：主页面 Presenter 实现
 */
class NittyTabPresenter(private val iView: IViewContract.INittyTabView): CommonPresenter(iView) {
    //val 是不可变的 var 可变的
    private val tabIconNormalList = arrayListOf(
        R.mipmap.nitty_main_tab1_normal,
        R.mipmap.nitty_main_tab2_normal,
        R.mipmap.nitty_main_tab3_normal,
        R.mipmap.nitty_main_tab4_normal
    )
    private val tabIconSelectedList = arrayListOf(
        R.mipmap.nitty_main_tab1_selected,
        R.mipmap.nitty_main_tab2_selected,
        R.mipmap.nitty_main_tab3_selected,
        R.mipmap.nitty_main_tab4_selected
    )
    private val tabTitleList = arrayListOf(
        R.string.nitty_main_tab1_title,
        R.string.nitty_main_tab2_title,
        R.string.nitty_main_tab3_title,
        R.string.nitty_main_tab4_title
    )
    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()
    var curtIndex = -1
    //首次进入APP，存在待还款订单需要跳转到待还款列表
    var isFirstIn = true

    //授信接口上次请求时间戳，防止3秒内重复请求
    private var requestCreditLastTime = 0L

    /**
     * 加载Tabbar数据
     */
    fun loadMainTabList(){
        tabList.clear()
        //tab
        for (i in 0 until tabTitleList.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabNormalIcon", tabIconNormalList[i])
            tabObj.put("tabSelectedIcon", tabIconSelectedList[i])
            tabObj.put("tabTitle", getString(tabTitleList[i]))
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        iView.showNittyTabList(tabList)
    }

    /**
     * 切换Tab
     */
    fun setMainCurrentItemIndex(index: Int) {
        curtIndex = index
        for (tabObj in tabList) {
            when (tabObj.optInt("tabId")) {
                index -> {
                    tabObj.put("isSelect", true)
                }
                else -> {
                    tabObj.put("isSelect", false)
                }
            }
        }
        iView.notifyNittyTabDataChanged(index)

        when(index){
            2 -> {
                //是否为浅色模式
                NittyTitleBarUtil.setStatusBarLightMode(iView.getAct(), true)
            }
            else -> {
                NittyTitleBarUtil.setStatusBarLightMode(iView.getAct(), false)
            }
        }
    }

    /**
     * 获取总流程
     */
    fun loadAppProcessAction() {
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_PROCESS_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Account Info")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("account_info")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    steps.put("sefie_info")
//                    steps.put("ocr_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    //保存用户流程数据
                    NittyProcessHelper.saveAuthProcessData(obj)

                    // 上次请求授信接口的时间是否超过3秒
                    val isRequestCredit = System.currentTimeMillis() - requestCreditLastTime > 3000
                    //进件信息已完成 - 需要授信状态完成之后通知 刷新进件信息
                    if (NittyProcessHelper.getAuthProcessList().size == 0 && isRequestCredit){
                        loadNittyCreditStatusAction()
                    } else {//进件信息 未完成 - 直接通知刷新进件信息完成
                        //通知全局流程刷新完成
                        iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESHED))
                    }

                    // TODO: 2024-11-20 新增需求 此处需要判断是否需要校验手机号
                    if (NittyProcessHelper.isCheckWhatsApp() || NittyProcessHelper.isCheckSMS()){
                        iView.showNittyCheckNumberPage()
                    }
                }
            }
            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.hiddenNittyLoading()
            }
        })
    }

    /**
     * 获取授信状态
     * status:
     *  PASSED(跳过该流程)
     *  REJECTED(跳拒绝页面)
     *  CREATED(可再次请求)
     */
    fun loadNittyCreditStatusAction(){
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_CREDIT_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    requestCreditLastTime = System.currentTimeMillis()
                    val creditStatus = obj.optString("status")
                    NittyCreditStatusHelper.saveNittyCreditStatus(creditStatus)
                    //刷新流程信息完成
                    iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_PROCESS_REFRESHED))
                    //通知全局授信状态刷新完成
                    iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_CREDIT_REFRESHED))
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取订单列表
     */
    fun loadOrderListAction(){
        val httpUrl = NittyApiUrl.getHttpUrl()
        val params = JSONObject().addCommonParams().apply {
            put("xd304965bcd9478080", NittyApiPath.NITTY_PATH.NITTY_API_LOAN_ORDER_PATH)
        }
        doHttpPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //保存当前时间戳,用于计算待还款订单剩余时长
                    obj.put("timeStamp",data.optLong("timp"))
                    NittyOrderHelper.saveNittyOrderData(obj)

                    val repayList = NittyOrderHelper.getNittyOrderRepayList()
                    //存在待还款订单 ，切换到待还款tab
                    if (repayList.size > 0 && isFirstIn){
                        isFirstIn = false
                        iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_SHOW_REPAY))
                    }
                    //通知全局订单刷新完成
                    iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_REFRESHED))
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                iView.getAct().publishEventData(NittyEventData(NittyEventData.TYPE.NITTY_ORDER_FINISHED))
            }
        })
    }
}